package com.ruoyi.report.forms.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.report.forms.domain.CngScadaRealtimeMonitoringHour;
import com.ruoyi.report.forms.domain.CtUser;
import com.ruoyi.report.forms.domain.DispatchAccessDataDay;
import com.ruoyi.report.forms.domain.DispatchChangeShifts;
import com.ruoyi.report.forms.domain.vo.ShiftsContentVO;
import com.ruoyi.report.forms.service.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class DataSelect {

    SXSSFSheet sheet;
    JSONArray bindata;
    String date;
    String month;

    // 场站设备小时数据
    List<CngScadaRealtimeMonitoringHour> station_day;
    List<CngScadaRealtimeMonitoringHour> station_day_custom;
    // 场站设备日数据
    HashMap<String, List<CngScadaRealtimeMonitoringHour>> station_month;
    HashMap<String, List<CngScadaRealtimeMonitoringHour>> station_month_custom;
    // 接入点数据
    List<DispatchAccessDataDay> into_out;
    // 交接班数据
    List<ShiftsContentVO> shift_turnover_station; // 场站
    List<DispatchChangeShifts> shift_turnover_center; // 调度中心
    List<List<CtUser>> shift_turnover_user; // 调度中心人员

    static String[] DayHourArr = {"07:00:00", "08:00:00", "09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00", "18:00:00", "19:00:00", "20:00:00", "21:00:00", "22:00:00", "23:00:00", "00:00:00", "01:00:00", "02:00:00", "03:00:00", "04:00:00", "05:00:00", "06:00:00", "07:00:00"};

    public DataSelect(JSONArray _bindata, String _date, String _month) {
        bindata = _bindata;
        date = _date;
        month = _month;

        GetData();
    }

    public DataSelect(SXSSFSheet _sheet, JSONArray _bindata, String _date, String _month) {
        sheet = _sheet;
        bindata = _bindata;
        date = _date;
        month = _month;

        GetData();
    }

    private void GetData() {
        StringBuilder station_day_ids = new StringBuilder();
        ArrayList<HashMap<String, String>> station_month_ids = new ArrayList<>();
        StringBuilder into_out_ids = new StringBuilder();
        String shift_turnover_stationid = "";
        String shift_turnover_stationType = "";
        for (int i = 0; i < bindata.size(); i++) {
            JSONObject data = bindata.getJSONObject(i);
            switch (data.getString("type")) {
                case "station_day":// 场站设备小时数据
                    if (!station_day_ids.toString().equals("")) {
                        station_day_ids.append(",");
                    }
                    station_day_ids.append(data.getString("attributeId"));
                    break;
                case "station_month":
                case "station_month_calc":
                    HashMap<String, String> tmp = new HashMap<>();
                    tmp.put("attributeId", data.getString("attributeId"));
                    tmp.put("hour", data.getString("hour"));
                    tmp.put("hash", data.getString("hash"));
                    station_month_ids.add(tmp);
                    break;
                case "into_out":// 接入点数据
                    if (!into_out_ids.toString().equals("")) {
                        into_out_ids.append(",");
                    }
                    into_out_ids.append(data.getString("intoId"));
                    break;
                case "shift_turnover":// 交接班
                    if (!data.getString("stationId").equals("diaoduzhongxin")) {
                        shift_turnover_stationType = Optional.ofNullable(data.getString("shift")).orElse("");
                        shift_turnover_stationid = data.getString("stationId");
                    }
                    break;
            }
        }

        // 处理日期
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate;
        try {
            startDate = sdFormat.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DATE, 1);
        Date endDate = calendar.getTime();

        // 获取场站日数据
        CngScadaRealtimeMonitoringHour cngScadaRealtimeMonitoringHour = new CngScadaRealtimeMonitoringHour();
        cngScadaRealtimeMonitoringHour.setAttributeId(station_day_ids.toString());
        // 有些数据需要用到今日7点至次日7点的数据，所以这里这么查询，标准的返回应该是25条
        cngScadaRealtimeMonitoringHour.setStartTime(sdFormat.format(startDate) + " 07:00:00");
        cngScadaRealtimeMonitoringHour.setEndTime(sdFormat.format(endDate) + " 07:00:00");
        ICngScadaRealtimeMonitoringHourService cngScadaRealtimeMonitoringHourService = SpringUtils.getBean(ICngScadaRealtimeMonitoringHourService.class);
        station_day = cngScadaRealtimeMonitoringHourService.selectCngScadaRealtimeMonitoringHourList(cngScadaRealtimeMonitoringHour);
        station_day_custom = cngScadaRealtimeMonitoringHourService.selectCngScadaRealtimeMonitoringHourCustomList(cngScadaRealtimeMonitoringHour);

        // 获取场站月数据
        station_month = new HashMap<>();
        station_month_custom = new HashMap<>();
        for (HashMap<String, String> tmp : station_month_ids) {
            cngScadaRealtimeMonitoringHour = new CngScadaRealtimeMonitoringHour();
            cngScadaRealtimeMonitoringHour.setAttributeId(tmp.get("attributeId"));

            cngScadaRealtimeMonitoringHour.setStartTime(month);
            String hour = tmp.get("hour");
            if (hour == null || hour.isEmpty()) {
                cngScadaRealtimeMonitoringHour.setEndTime("07:00:00");
            } else {
                cngScadaRealtimeMonitoringHour.setEndTime(String.format("%02d", Integer.parseInt(hour)) + ":00:00");
            }

            station_month.put(tmp.get("hash"), cngScadaRealtimeMonitoringHourService.selectCngScadaRealtimeMonitoringMonthList(cngScadaRealtimeMonitoringHour));
            station_month_custom.put(tmp.get("hash"), cngScadaRealtimeMonitoringHourService.selectCngScadaRealtimeMonitoringMonthCustomList(cngScadaRealtimeMonitoringHour));
        }

        // 获取接入点数据
        DispatchAccessDataDay dispatchAccessDataDay = new DispatchAccessDataDay();
        dispatchAccessDataDay.setAccessId(into_out_ids.toString());
        dispatchAccessDataDay.setDataTime(startDate);
        IDispatchAccessDataDayService dispatchAccessDataDayService = SpringUtils.getBean(IDispatchAccessDataDayService.class);
        into_out = dispatchAccessDataDayService.selectDispatchAccessDataDayList(dispatchAccessDataDay);

        // 获取交接班数据
        if (!shift_turnover_stationid.isEmpty()) {
            // 场站
            IPatrolInspectionChangeShiftsService patrolInspectionChangeShiftsService = SpringUtils.getBean(IPatrolInspectionChangeShiftsService.class);
            if (shift_turnover_stationType.equals("month-one")) {
                shift_turnover_station = patrolInspectionChangeShiftsService.selectShiftsInfoForMonth(shift_turnover_stationid, month);
            } else {
                shift_turnover_station = patrolInspectionChangeShiftsService.selectShiftsInfo(shift_turnover_stationid, sdFormat.format(startDate));
            }
        } else {
            // 调度中心
            SimpleDateFormat shift_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            IDispatchChangeShiftsService dispatchChangeShiftsService = SpringUtils.getBean(IDispatchChangeShiftsService.class);
            DispatchChangeShifts dispatchChangeShifts = new DispatchChangeShifts();
            try {
                dispatchChangeShifts.setJiebanStartTime(shift_format.parse(sdFormat.format(startDate) + " 08:00:00"));
                dispatchChangeShifts.setJiebanEndTime(shift_format.parse(sdFormat.format(endDate) + " 08:00:00"));
                dispatchChangeShifts.setSuccessionType("1");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            shift_turnover_center = dispatchChangeShiftsService.selectDispatchChangeShiftsList(dispatchChangeShifts);

            // 调度中心的值班人员
            ICtUserService ctUserService = SpringUtils.getBean(ICtUserService.class);
            shift_turnover_user = new ArrayList<>();
            for (DispatchChangeShifts changeShifts : shift_turnover_center) {
                CtUser ctUser = new CtUser();
                ctUser.setUserId(changeShifts.getSuccessionUsers());
                shift_turnover_user.add(ctUserService.selectCtUserList(ctUser));
            }
        }
    }

    // 处理调度中心的交接班记事数据，非常非常的麻烦。
    static String[] getRecordByList(String notes, String record) {
        String[] arrNotes = new String[0];
        String[] arrRecord = new String[0];
        if (notes != null) {
            arrNotes = notes.split("\n");
        }
        if (record != null) {
            arrRecord = record.split("\n");
        }
        String[] arrAll = Stream.concat(Arrays.stream(arrNotes), Arrays.stream(arrRecord)).toArray(String[]::new);
        HashMap<String, String> mapAll = new HashMap<>();

        String pattern = "^[\\d]?[\\d][:][\\d][\\d]";
        Pattern compile = Pattern.compile(pattern);
        for (String s : arrAll) {
            Matcher matcher = compile.matcher(s);
            if (matcher.find()) {
                String time = s.substring(matcher.start(), matcher.end());
                String[] parts = time.split(":");
                int hour = Integer.parseInt(parts[0]);
                int minute = Integer.parseInt(parts[1]);
                mapAll.put(String.format("%02d:%02d", hour, minute), s);
            }
        }

        Object[] keys = mapAll.keySet().toArray();
        Arrays.sort(keys);

        ArrayList<String> arr1 = new ArrayList<>();
        ArrayList<String> arr2 = new ArrayList<>();
        for (Object o : keys) {
            String key = (String) o;
            if (key.compareTo("08:00") >= 0) {
                arr1.add(mapAll.get(key));
            } else {
                arr2.add(mapAll.get(key));
            }
        }

        return new String[]{String.join("\n", arr1), String.join("\n", arr2)};
    }
}
